using System;

namespace Nice157Advices.Advices
{
    /// <summary>
    /// 11、区别对待==和Equals
    /// 12、重写Equals时也要重写GetHashCode
    /// </summary>
    public static class _11_12
    {
        /**
         * 一般来说，对于引用类型，我们要定义“值相等性”，应该仅仅去重载Equals方法，
         * 同时让"=="表示“引用相等性”
         */

        public static void Go ()
        {
            var a = 1;
            var b = 1;

            Console.WriteLine ($"a == b: {a == b}");
            Console.WriteLine ($"a equals b: {a.Equals(b)}");

            var c = new Salary2 () { RMB = 1 };
            var d = new Salary2 () { RMB = 1 };
            Console.WriteLine ($"c hashcode: {c.GetHashCode()}; d hashcode: {d.GetHashCode()}");

            Console.WriteLine ($"c == d: {c == d}");
            Console.WriteLine ($"c equals d: {c.Equals(d)}");
        }

        private class Salary2
        {
            public int RMB { get; set; }

            public override bool Equals (object obj) =>
                RMB == (obj as Salary2).RMB;

            /**
             * 重写Equals方法也要重写GetHashCode方法
             * 否则在某些需要用到对象的hashCode值比较的地方时会导致Equals相等的情况下失败的问题，比如Dictionary的值为对象实例时
             */

            /**
             * 另外有可能出现 this.RMB 值过长过大 导致 this.RMB 不同但 hashCode 相等，此时需要更多的操作了（这里就不写了...)
             */

            public override int GetHashCode () =>
                this.RMB.GetHashCode ();
        }
    }
}